using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using AnalyticsGadget.Models;
using EPiServer.Data.Dynamic;


namespace AnalyticsGadget.Controllers
{
    public abstract class BaseStatisticsController : Controller
    {      
        public ActionResult Index(Guid GadgetId)
        {
            ReportSettings settings = LoadSettings(GadgetId);
            
            ReportModel model = new ReportModel();
            model.Report = GetReport(settings.ProfileID, settings.Timespan);
            
            ReportMetaData metaData = new ReportMetaData();
            metaData.Profiles = StatisticsHelper.Profiles;
            metaData.Timespans = StatisticsHelper.Timespans;
            model.MetaData = metaData;

            return View("Index", model);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult Update(string profileID, Timespan timespan, Guid GadgetId)
        {
            ReportSettings settings = LoadSettings(GadgetId);
            settings.Timespan = timespan;
            settings.ProfileID = profileID;
            SaveSettings(settings);

            ReportModel model = new ReportModel();
            model.Report = GetReport(settings.ProfileID, settings.Timespan);

            ReportMetaData metaData = new ReportMetaData();
            metaData.Profiles = StatisticsHelper.Profiles;
            metaData.Timespans = StatisticsHelper.Timespans;
            model.MetaData = metaData;

            return View("Index", model);
        }

        protected abstract Report GetReport(string profileID, Timespan timespan);

        protected DynamicDataStore GetReportSettingsStore()
        {
            var store = DynamicDataStoreFactory.Instance.GetStore("AnalyticsGadgetStore");
            if (store == null)
            {
                store = DynamicDataStoreFactory.Instance.CreateStore("AnalyticsGadgetStore", typeof(ReportSettings));
            }
            return store;
        }

        protected void SaveSettings(ReportSettings settings)
        {
            
            GetReportSettingsStore().Save(settings);
        }

        protected ReportSettings LoadSettings(Guid gadgetId)
        {

            ReportSettings settings = (ReportSettings)GetReportSettingsStore().Find("GadgetId", gadgetId).FirstOrDefault();

            if (settings != null)
            {
                return settings;
            }
            else
            {
                settings = new ReportSettings()
                {
                    GadgetId = gadgetId,
                    ProfileID = StatisticsHelper.DefaultProfile.ID,
                    Timespan = Timespan.Month
                };

                GetReportSettingsStore().Save(settings);

                return settings;
            }
        }
    }
}
